// pages/productDetails/productDetails.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    numbers: 1,
    modifyPriceCol: true,
    share:1,
    share_id:'',
    preferentialPrice:0,
    cartCount:0,
    authorize:true //授权
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu() // 隐藏分享按钮

    if (app.globalData.shopId) {
      this.setData({
        shop_id: app.globalData.shopId
      })
    }

    if (options.uid) {
      this.setData({
        uid: options.uid
      })
    }

    if (options.sku_code) {
      this.setData({
        sku_code: options.sku_code
      })
    }
    this.getProductInfo();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      user_flag: app.globalData.accountInfo.user_flag
    })
    this.cartNum();
  },

  getProductInfo: function() {
    var that = this;
    var params = new Object()
    params.sku_code = this.data.sku_code;
    // if (this.data.shop_id) {
    //   params.shop_id = this.data.shop_id;
    // }
    util.showLoading("数据加载中..");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'goods/getInfo',
      success: function(res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          that.setData({
            rawData: res.data.data
            // newPrice: res.data.data.current_price
          });
        }

      },
      fail: function(fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },
  addNum: function() {
    var num = this.data.numbers;
    num++;
    this.setData({
      numbers: num
    })
  },
  minusNum: function() {
    var num = this.data.numbers;
    if (num > 1) {
      num--;
    }
    this.setData({
      numbers: num
    })
  },
  // 加入购物车
  addCart: function() {
    var that = this;
    var params = new Object()
    params.sku_code = this.data.sku_code;
    params.num = this.data.numbers;
    if (this.data.shop_id) {
      params.shop_id = this.data.shop_id;
    }
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/addGoods',
      success: function(res) {
        if (util.isEmpty(res.data.code)) {
          util.showSuccess("加入成功");
          that.cartNum();
        } else {
          util.showStatus(res.data.message)
        }

      },
      fail: function(fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },
  //购物车商品数量
  cartNum:function(){
    var that = this;
    api.POST({
      params: '',
      url: app.globalData.base_url + 'shoppingcart/countGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          // util.showSuccess("加入成功")
          // console.log(res)
          that.setData({
            cartCount: res.data.data.countNum
          })
        }

      },
      fail: function (fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },
  // 立即购买
  pay: function() {
    var orderList = [];
    var box = new Object();
    box.num = this.data.numbers;
    box.stock = this.data.rawData.stock;
    if (this.data.shop_id) {
      box.shop_id = this.data.shop_id;
      var shop_id = this.data.shop_id;
      if (box.num > box.stock) {
        util.showStatus("库存不足");
        return;
      }
    }
    if (this.data.uid) {
      var uid = this.data.uid;
    } else {
      var uid = ''
    }

    box.sku_code = this.data.sku_code;
    box.current_price = this.data.rawData.current_price;
    box.gname = this.data.rawData.gname;
    box.image = this.data.rawData.image;
    box.degree = this.data.rawData.degree;
    box.degree_unit = this.data.rawData.degree_unit;
    box.volume = this.data.rawData.volume;
    box.volume_unit = this.data.rawData.volume_unit;
    box.total = (this.data.numbers * this.data.rawData.current_price).toFixed(2);
    orderList.push(box);
    wx.setStorageSync('orderList', orderList);
    if (shop_id) {
      wx.navigateTo({
        url: '../order/order?shop_id=' + shop_id
      })
    } else if (uid) {
      wx.navigateTo({
        url: '../order/order?uid=' + uid
      })
    } else {
      wx.navigateTo({
        url: '../order/order'
      })
    }
  },
  linkCart: function() {
    wx.navigateTo({
      url: '../cart/cart'
    })
  },
  onShareAppMessage: function(res) {

    var that = this;
    var uid = '&uid=' + app.globalData.accountInfo.uid;
    if (this.data.share_id){
      var share_id = '&share_id=' + this.data.share_id;
      var url = '/pages/shareProduct/shareProduct?sku_code=' + that.data.sku_code + uid + share_id
    }else{
      var share_id=''
      var url = '/pages/productDetails/productDetails?sku_code=' + that.data.sku_code + uid
    }

    setTimeout(function(){

    },1000)

    
    
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: that.data.rawData.gname,
        path: url,
        imageUrl: that.data.rawData.share_img,
        success: function(res) {
          // that.closeModifyPrice();
          // console.log("222");
          that.setData({
            share:"",
            share_id:"",
            modifyPriceCol:true
          })
        },
        fail: function(res) {
          // 转发失败
        }
      }
    }
  },
  modifyPrice: function() {
    this.setData({
      modifyPriceCol: false,
      share: 1
    })
  },
  closeModifyPrice: function() {
    this.setData({
      modifyPriceCol: true,
      share: 1
    })
  },
  newPrice: function(e) {
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    var money = e.detail.value/1
    var newPrice = this.data.newPrice/1
    var current_price = this.data.rawData.current_price / 1
    var minprice = this.data.rawData.share_bottom_price/1
    var preferentialPrice = this.data.preferentialPrice
    if (reg.test(money) ) {
      // if (money < minprice){
      //   money = minprice
      // } else if (money > current_price){
      //   money = current_price
      // }
      // console.log(money);
      if (money!=0){
        money = money.toFixed(2);
        preferentialPrice = (current_price - money).toFixed(2);
      }else{
        money=''
        preferentialPrice = (current_price - money).toFixed(2);
      }
      
    } else {
      money = ""
    }
    this.setData({
      newPrice: money,
      preferentialPrice: preferentialPrice
    })
  },
  //确认修改价格
  submitModifyPrice: function () {
    var that = this;
    var params = new Object()
    
    
    var timer = setTimeout(function(){

      var newPrice = parseFloat(that.data.newPrice)
      var share_bottom_price = parseFloat(that.data.rawData.share_bottom_price)
      var current_price = parseFloat(that.data.rawData.current_price)

      if (isNaN(newPrice)) {
        newPrice = 0
      }
      if (newPrice < share_bottom_price) {
        util.showStatus("价格不得低于" + share_bottom_price);
        return false
      }
      if (newPrice > current_price) {
        util.showStatus("价格不得高于" + current_price);
        return false
      }


      params.sku_code = that.data.rawData.sku_code;
      params.share_price = that.data.newPrice;
      api.POST({
        params: params,
        url: app.globalData.base_url + 'goods/shareSub',
        success: function (res) {
          if (util.isEmpty(res.data.code)) {
            util.showStatus("修改成功，请点击分享")
            that.setData({
              share: 2,
              share_id: res.data.data.share_id,
              share_img: res.data.data.code_img,
            })
            clearTimeout(timer);
          } else {
            util.showStatus(res.data.message)
          }

        },
        fail: function (fail) {
          util.showErrorPath("../../../", "获取失败，请检查网络");
        }
      })
    },300)
  },
  priceInput:function(){
    this.setData({
      share: 1
    })
  },

  getImageInfo: function () {
    var that = this;
    var img = this.data.share_img
    wx.getImageInfo({
      src: img,
      success: function (res) {
        that.setData({
          share_qr_code: res.path
        })
        setTimeout(function () {
          that.saveImage()
        }, 500);
      }
    })
  },
  handler: function (e) {
    if (e.detail.authSetting["scope.writePhotosAlbum"]) {
      this.saveImage();
      this.setData({
        authorize: true
      })
    }
  },
  saveImage: function () {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.share_qr_code,
      success(res) {
        util.showError('保存图片成功')
      },
      fail: function (fail) {
        if (fail.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
          //请求授权
          // wx.showModal({
          //   title: '提示',
          //   showCancel: false,
          //   content: '请点击页面授权按钮，否则无法保存图片到相册'
          // })
          that.setData({
            authorize:false
          })
        }
      }
    })
  }


})